<template>
  <main class="flex-1 max-w-7xl mx-auto w-full flex mt-4 px-4 gap-4">
    <aside class="w-64 bg-dark-lighter rounded p-4">
      <div class="flex items-center justify-between mb-4">
        <h3 class="font-semibold">历史记录</h3>
        <button class="text-gray-400 hover:text-primary">
          <i class="fas fa-trash"></i>
        </button>
      </div>
      <div class="space-y-2">
        <div v-for="(record, index) in historyRecords"
             :key="index"
             :class="['p-2 rounded cursor-pointer hover:bg-opacity-20 hover:bg-primary',
                       { 'bg-primary bg-opacity-10': index === 0 }]">
          <p class="text-sm text-gray-300 truncate">{{ record.question }}</p>
          <p class="text-xs text-gray-500">{{ record.time }}</p>
        </div>
      </div>
    </aside>

    <section class="flex-1 bg-dark-lighter rounded p-4 flex flex-col">
      <div class="flex-1 overflow-y-auto mb-4 space-y-4" style="width: 100%">
        <div v-for="(message, index) in messages" :key="index" :class="['flex items-start', message.isUser ? 'justify-end' : '']">
          <template v-if="!message.isUser">
            <div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center mr-3">
              <i class="fas fa-robot"></i>
            </div>
          </template>
          <div :class="['chat-message', message.isUser ? 'bg-primary bg-opacity-20' : 'bg-gray-800', 'rounded-lg p-3', 'group relative']">
            <template v-if="!message.isUser && message.thinking">
              <div class="mb-3">
                <button class="flex items-center text-sm text-gray-400 hover:text-primary" @click="toggleThinking(index)">
                  <i class="fas fa-lightbulb mr-2"></i>
                  <span>查看思考过程</span>
                  <i class="fas fa-chevron-down ml-2"></i>
                </button>
                <div v-show="message.showThinking" class="mt-2 p-3 bg-gray-700 rounded text-sm">
                  <p v-for="(think, tIndex) in message.thinking" :key="tIndex">{{ think }}</p>
                </div>
              </div>
            </template>
            <div v-html="message.content" :class="{ 'prose prose-invert max-w-none': !message.isUser }"></div>
            <div v-if="!message.isUser" class="absolute bottom-0 left-0 translate-y-full opacity-0 group-hover:opacity-100 flex space-x-2 mt-2 transition-opacity">
              <button v-for="action in messageActions" :key="action.icon" class="w-8 h-8 flex items-center justify-center rounded hover:bg-gray-700" :title="action.title">
                <i :class="['fas', action.icon]"></i>
              </button>
            </div>
          </div>
          <template v-if="message.isUser">
            <div class="w-8 h-8 rounded-full bg-gray-600 flex items-center justify-center ml-3">
              <i class="fas fa-user"></i>
            </div>
          </template>
        </div>
      </div>

      <div class="flex flex-col bg-gray-800 rounded-lg p-2">
        <div class="flex items-start space-x-2">
            <textarea ref="messageInput" v-model="inputMessage" placeholder="输入您的问题..."
                      class="flex-1 bg-transparent border-none text-white px-3 py-2 resize-none min-h-[40px] max-h-[120px] overflow-y-auto"
                      :style="{ height: textareaHeight + 'px' }"
                      @input="adjustTextareaHeight"
                      @keydown.enter.prevent="sendMessage"></textarea>
          <button class="bg-primary px-4 py-2 !rounded-button whitespace-nowrap" @click="sendMessage">
            <i class="fas fa-paper-plane mr-2"></i>发送
          </button>
        </div>
        <div class="flex items-center gap-2 mt-2 px-3">
          <div class="flex flex-wrap gap-2 items-center">
            <button v-for="command in commands" :key="command.text"
                    class="text-gray-400 hover:text-primary border border-gray-600 px-2 py-1 rounded text-sm hover:border-primary whitespace-nowrap group relative"
                    @click="addActiveCommand(command)">
              {{ command.text }}
              <div class="absolute bottom-full left-0 mb-2 hidden group-hover:block bg-gray-700 text-white text-xs p-1 rounded whitespace-nowrap">
                {{ command.tooltip }}
              </div>
            </button>
          </div>
          <div id="activeCommands" class="flex-1 flex gap-2">
              <span v-for="(cmd, index) in activeCommands" :key="index"
                    class="bg-gray-700 text-white px-2 py-1 rounded text-sm flex items-center gap-1">
                {{ cmd }}<button class="hover:text-red-500" @click="removeActiveCommand(index)">×</button>
              </span>
          </div>
        </div>
      </div>
    </section>

    <aside class="w-64 bg-dark-lighter rounded p-4">
      <h3 class="font-semibold mb-4">快捷工具</h3>
      <div class="space-y-2">
        <button v-for="tool in quickTools" :key="tool.text"
                class="w-full text-left px-3 py-2 rounded hover:bg-primary hover:bg-opacity-10">
          <i :class="['fas', tool.icon, 'mr-2']"></i>{{ tool.text }}
        </button>
      </div>
    </aside>
  </main>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { getModelList, chat } from '../api/biz'

var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
  // var messages = document.getElementById('messages')
  // var message = document.createElement('li')
  // var content = document.createTextNode(event.data)
  // message.appendChild(content)
  // messages.appendChild(message)

  console.log('---event---')
  console.log(event.data)
  const result = event.data
  const resultJson = JSON.parse(result)
  console.log(resultJson)

  messages.value.push({
    isUser: false,
    thinking: resultJson.output.thinking,
    content: resultJson.output.content,
    showThinking: false
  });
};

const historyRecords = [
  { question: '如何提高工作效率？', time: '2023-12-20 14:30' },
  { question: 'Python 编程入门指南', time: '2023-12-20 13:15' },
  { question: 'AI 发展趋势分析', time: '2023-12-20 11:45' }
];

const messages = ref([
  {
    isUser: false,
    content: '您好！我是您的 AI 助手。我可以帮您解答问题、提供建议，或者一起探讨有趣的话题。请问有什么我可以帮您的吗？'
  },
  {
    isUser: true,
    content: '你好！我想了解如何提高工作效率。'
  },
  {
    isUser: false,
    content: `<div class="prose prose-invert max-w-none">
    <h4>提高工作效率有几个关键方面：</h4>
    1. 制定明确的目标和计划<br>
    2. 使用番茄工作法进行时间管理<br>
    3. 减少干扰，保持专注<br>
    4. 适时休息，保持精力充沛<br>
    5. 利用效率工具，如任务管理软件<br><br>
    您想了解哪个方面的具体建议呢？</div>`,
    thinking: [
      '1. 分析用户需求：用户想了解提高工作效率的方法',
      '2. 确定关键要素：目标设定、时间管理、专注度、休息、工具使用',
      '3. 提供具体建议：列举实用可行的方法',
      '4. 引导深入交流：询问用户感兴趣的具体方面'
    ],
    showThinking: false
  }
]);

const messageActions = [
  { icon: 'fa-sync-alt', title: '重新生成' },
  { icon: 'fa-copy', title: '复制全部' },
  { icon: 'fa-lightbulb', title: '复制思考' },
  { icon: 'fa-clipboard', title: '复制结果' },
  { icon: 'fa-trash', title: '删除' },
  { icon: 'fa-thumbs-up', title: '点赞' },
  { icon: 'fa-thumbs-down', title: '不喜欢' }
];

const commands = ref([
  { text: '/image', tooltip: '点击插入图片指令' },
  { text: '/history', tooltip: '查看历史记录' },
  { text: '#code', tooltip: '生成代码模式' },
  { text: '/help', tooltip: '查看帮助信息' },
  { text: '/clear', tooltip: '清空当前会话' }
]);

const quickTools = ref([
  { text: '智能优化', icon: 'fa-wand-magic-sparkles' },
  { text: '翻译助手', icon: 'fa-language' },
  { text: '代码生成', icon: 'fa-code' },
  { text: '图片处理', icon: 'fa-image' }
]);

const inputMessage = ref('');
const textareaHeight = ref(40);
const activeCommands = ref<string[]>([]);
const messageInput = ref<HTMLTextAreaElement>();

const adjustTextareaHeight = () => {
  const textarea = messageInput.value;
  if (textarea) {
    textarea.style.height = '40px';
    textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;
    textareaHeight.value = Math.min(textarea.scrollHeight, 120);
  }
};

const sendMessage = async () => {
  if (inputMessage.value.trim()) {
    const prompt = inputMessage.value.trim()
    messages.value.push({
      isUser: true,
      content: inputMessage.value
    });
    inputMessage.value = '';
    textareaHeight.value = 40;

    console.log('---message---')
    console.log(prompt)

    ws.send(prompt);

    // const resp = await chat({
    //   model: '',
    //   prompt: prompt
    // })
    // console.log(resp)
  }
};

const toggleThinking = (index: number) => {
  if (messages.value[index].thinking) {
    messages.value[index].showThinking = !messages.value[index].showThinking;
  }
};

const addActiveCommand = (command: { text: string }) => {
  if (!activeCommands.value.includes(command.text)) {
    activeCommands.value.push(command.text);
  }
};

const removeActiveCommand = (index: number) => {
  activeCommands.value.splice(index, 1);
};
</script>


<style scoped>

</style>
